import logging
import random
import datetime
import hashlib
import json

from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect

from fidoweb.lib.base import BaseController, render, Session
from fidoweb.model.user import User, Profession
from fidoweb.model.map import School

log = logging.getLogger(__name__)

class LoginController(BaseController) :
	_popupDialogs = {
		'login' : '/login/popupdialog_login.mako',
	}
	
	def index(self) :
		if (self._isLoggedIn()) :
			c.title = 'User Panel'
			c.header = render('global/globalheader.mako')
			c.content = render('/login/userpanel.mako')
			return render('/global/global.mako')
		else :
			c.title = 'Login'
			c.header = render('global/globalheader.mako')
			c.content = render('/login/login.mako')
			return render('/global/global.mako')
	
	def checkFidocardState(self) :
		from fidoweb.model.user import User
		fc = request.POST['fidocard']
		users = Session.query(User).filter_by(fidocard = fc)
		if (users.count() == 0) : return 'empty'
		user = users.first()
		if (user.websiteSignup == True) : return 'signup'
		return 'not signup'

	def doSignup(self) :
		fidocard = request.POST['fidocard']
		password = request.POST['password']
		users = Session.query(User).filter_by(fidocard = fidocard)
		if (users.count() == 0) : return 'fail'
		user = users.first()
		user.password = password
		user.websiteSignup = True
		Session.commit()
		return 'success'
	
	def doLogin(self) :
		if (not('method' in request.POST) or not ('username' in request.POST) or not ('password' in request.POST)) :
			return 'fail'
		if (request.POST['method'] == 'mobile') :
			users = Session.query(User).filter_by(mobile = request.POST['username'])
		else :
			users = Session.query(User).filter_by(fidocard = request.POST['username'])
		password = request.POST['password']
		if (users.count() == 0) : return 'wrong username'
		user = users.first()
		if (('loginCode' in session) and ('loginCodeGeneratingTime' in session) and (datetime.datetime.now() - session['loginCodeGeneratingTime']).seconds < 20) :
			p = hashlib.sha512(session['loginCode'] + user.password).hexdigest()
			if (p == password) :
				session['mobile'] = user.mobile
				session['loggedIn'] = True
				session.save()
				return 'success'
			else :
				return 'wrong password'
		return 'fail'

	def getLoginCode(self) :
		res = ''
		for i in range(0, 20) :
			res += chr(random.randint(48, 122))
		session['loginCode'] = res
		session['loginCodeGeneratingTime'] = datetime.datetime.now()
		session.save()
		return res
		
	def getSchools(self) :
		response.headers['Content-Type'] = 'application/x-json'
		ret = list()
		for school in Session.query(School) :
			ret.append([school.id, school.name.decode('utf8')])
		return json.dumps(ret)
	
	def getProfessions(self) :
		response.headers['Content-Type'] = 'application/x-json'
		ret = list()
		for pro in Session.query(Profession) :
			ret.append([pro.id, pro.name.decode('utf8')])
		return json.dumps(ret)
		
	def getPopupDialog(self) :
		if (not 'name' in request.POST) : return ''
		name = request.POST['name']
		if (self._popupDialogs.get(name) == None) :
			return ''
		else :
			return render(self._popupDialogs[name])
	
	def getLoginUser(self) :
		response.headers['Content-Type'] = 'application/x-json'
		ret = list()
		user = self._getLoginUser()
		if (user == None) :
			return json.dumps(ret)
		ret.append(user.name)
		ret.append(user.gender)
		ret.append(user.mobile)
		from fidoweb.lib.algorithm import dateToStr
		ret.append(dateToStr(user.birthday))
		ret.append(user.fidoPoints)
		ret.append(user.email)
		ret.append(user.fidocard)
		return json.dumps(ret)
	
	def getUserSchoolMapLocLikeCount(self) :
		response.headers['Content-Type'] = 'application/x-json'
		if ((not 'type' in request.GET) or (request.GET['type'] != 'like' and request.GET['type'] != 'dislike') and request.GET['type'] != 'all') :
			return ''
		like_type = request.GET['type']
		user = self._getLoginUser()
		if (user == None) : return ''
		from fidoweb.model.map import SchoolMapLoc_User
		if (like_type == 'all') :
			 ret = Session.query(SchoolMapLoc_User).filter_by(user_id = user.id).count()
		else :
			ret = Session.query(SchoolMapLoc_User).filter_by(user_id = user.id).filter_by(type = like_type).count()
		return json.dumps([ret])
		
	def getUserSchoolMapLocLike(self) :
		response.headers['Content-Type'] = 'application/x-json'
		ret = list()
		if ((not 'type' in request.GET) or (request.GET['type'] != 'like' and request.GET['type'] != 'dislike') and request.GET['type'] != 'all') :
			return json.dumps(ret)
		if ((not 'start' in request.GET) or (not 'end' in request.GET)) :
			return json.dumps(ret)
		like_type = request.GET['type']
		start = int(request.GET['start'])
		end = int(request.GET['end'])
		if (end - start > 20 or end - start < 0) :
			return json.dumps(ret)
		user = self._getLoginUser()
		if (user == None) :
			return json.dumps(ret)
		from fidoweb.model.map import SchoolMapLoc, SchoolMapLoc_User
		if (like_type == 'all') :
			userLocs = Session.query(SchoolMapLoc_User).filter_by(user_id = user.id).slice(start, end)
		else :
			userLocs = Session.query(SchoolMapLoc_User).filter_by(user_id = user.id).filter_by(type = like_type).slice(start, end)
		for userLoc in userLocs :
			locs = Session.query(SchoolMapLoc).filter_by(id = userLoc.schoolMapLoc_id)
			if (locs.count() == 0) : continue
			loc = locs.first()
			likeCount = Session.query(SchoolMapLoc_User).filter_by(schoolMapLoc_id = loc.id).filter_by(type = 'like').count()
			dislikeCount = Session.query(SchoolMapLoc_User).filter_by(schoolMapLoc_id = loc.id).filter_by(type = 'dislike').count()
			picList = list()
			for pic in loc.pics : 
				picList.append([pic.type, pic.filename])
			ret.append([loc.name, userLoc.type, loc.address, likeCount, dislikeCount, picList])
		return json.dumps(ret)
	
	def logout(self) :
		session.clear()
		session.save()
		return 'success'
	
	def signup(self) :
		from fidoweb.controllers.header import HeaderController
		hc = HeaderController()
		c.title = 'Signup'
		c.header = render('global/globalheader.mako')
		c.content = render('/login/signup.mako')
		return render('/global/global.mako')
	
	def _getLoginUser(self) :
		if (self._isLoggedIn()) :
			users = Session.query(User).filter_by(mobile = session['mobile']);
			if (users.count() > 0) :
				return users.first()
			else :
				return None
		else :
			return None

	def _isLoggedIn(self) :
		if (('mobile' in session) and ('loggedIn' in session) and session['loggedIn'] == True) : 
			return True
		else :
			return False
	
